package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.SharecartworegMapper;
import com.gljx.web.dao.SharecartworegentryMapper;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
@Controller
@RequestMapping("/")
public class ShareCarTwoRegContraller {

    @Autowired
    SharecartworegService sharecartworegService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    PersonController personController;
    @Autowired
    CoaceGroupController coaceGroupController;
    @Autowired
    StudentController studentController;
    @Autowired
    ExerciseCarPlanController exerciseCarPlanController;
    @Autowired
    SharecartworegMapper sharecartworegMapper;
    @Autowired
    MessageService messageService;
    @Autowired
    SharecartworegentryMapper sharecartworegentryMapper;
    @Autowired
    SharecarsubService sharecarsubService;
    @Autowired
    ChangecoachTwoService changecoachTwoService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CoaceGroupService coaceGroupService;
    @Autowired
    private RecordinentryService recordinentryService;
    @Autowired
    private ExerciseCarPlanService exerciseCarPlanService;
    @Autowired
    private CoachSubService coachSubService;


    /**
     * @Author lcx
     * @Date 2017/11/20 0020 上午 10:43
     * 查询科目二分车列表1
     */
    @RequestMapping("/querySharecartworeg/look.action")
    public String querySharecartworeg(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {


        PageBean<Sharecartworeg> pb = new PageBean<>();
        //获取操作人信息

        //deployProcess();


        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            //默认时间
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, null);
            } else {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            }
            //获取当前分页的值
            List<Sharecartworeg> sharecartworegList = pb.getBeanList();

            //把获取到的数据传回页面
            for (Sharecartworeg sharecartworeg : sharecartworegList) {
                //查询学员信息
                sharecartworeg.setSharecartworegentryList(sharecartworegService.selectSharecartworegentryByFid(sharecartworeg.getFid(), cfstudentname));

            }
            //合计信息总条数
           String messageAmount="共有"+pb.getTr()+"条信息";

            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("sharecartworegList", sharecartworegList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);
            request.setAttribute("activitiBPMN_KEY", ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/practiseCAR/ShareCarTwoReg/ShareCarTwoRegList";
    }

    /**
     * @Author lcx
     * @Date 2017/11/29 0029 上午 10:28
     * 如果编码为空默认按照业务日期排序分页显示
     * fnumber 编码
     * fdescription 简称
     * cfstudentname 学员姓名
     * beginTime 开始时间
     * endTime 结束时间
     */
    public PageBean<Sharecartworeg> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                                String fdescription, String cfstudentname,
                                                String beginTime, String endTime, String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT DISTINCT" +
                    "  R.FID," +
                    "  R.FNUMBER," +
                    "   TO_CHAR(R.FBIZDATE, 'YYYY-MM-DD') FBIZDATE," +
                    "   R.FDESCRIPTION," +
                    "  U1.NAME AS checkName," +
                    "  U2.NAME AS createName," +
                    "  r.CFBILLSTATE," +
                    "  r.fcreatetime" +
                    " FROM CT_DS_SHARECARTWOREG R" +
                    "  LEFT JOIN T_E_USER U1 ON R.FAUDITORID = U1.FID" +
                    "  LEFT JOIN T_E_USER U2 ON R.FCREATORID = U2.FID " +
                    "  LEFT JOIN CT_DS_SHARECARTWOREGentry R2 on r.fid = r2.FPARENTID " +
                    "  LEFT JOIN CT_DS_STUDENT S ON R2.CFSTUDENTID = S.FID" +
                    " where R.FCONTROLUNITID= '" + companyId + "' and r2.FPARENTID is not null");
            if (!"".equals(fnumber)) {
                psql.append(" and r.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and r.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" ORDER BY r.fcreatetime DESC");
        } else {
            psql.append("SELECT DISTINCT" +
                    "  R.FID," +
                    "  R.FNUMBER," +
                    "   TO_CHAR(R.FBIZDATE, 'YYYY-MM-DD') FBIZDATE," +
                    "   R.FDESCRIPTION," +
                    "  U1.NAME AS checkName," +
                    "  U2.NAME AS createName," +
                    "  r.CFBILLSTATE," +
                    "  r.fcreatetime" +
                    " FROM CT_DS_SHARECARTWOREG R" +
                    "  LEFT JOIN T_E_USER U1 ON R.FAUDITORID = U1.FID" +
                    "  LEFT JOIN T_E_USER U2 ON R.FCREATORID = U2.FID " +
                    "  LEFT JOIN CT_DS_SHARECARTWOREGentry R2 on r.fid = r2.FPARENTID " +
                    "  LEFT JOIN CT_DS_STUDENT S ON R2.CFSTUDENTID = S.FID" +
                    " where R.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and r.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and r.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append("and (r.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD'))" +
                    "  ORDER BY r.fcreatetime DESC");
        }

        int psize = 50; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = sharecartworegService.selectPage(pindex, psql.toString(), psize);
        PageBean<Sharecartworeg> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Sharecartworeg>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = sharecartworegService.selectPageCount(psql);
        return paramMap;
    }


    /**
     * @Author lcx
     * @Date 2017/11/20 0020 下午 3:12
     */
    @RequestMapping(value = "/go_add_Sharecartworeg")
    public String goAddSharecartworeg(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_SHARECARTWOREG", user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("KMEFC");

        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.MONTH, -3);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        //查询教练组信息
        Map map2 = coaceGroupController.getPageCoaceGroup(request, "", "", "0");
        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");

        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);

        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb2", map2.get("pb"));
        request.setAttribute("coacegroups", map2.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());

        request.setAttribute("alertType", alertType);


        return "/backHome/practiseCAR/ShareCarTwoReg/ShareCarTwoRegAdd";

    }

    @RequestMapping(value = "go_update_shareCarTwoReg")
    public String goUpdateShareCarTwoReg(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.MONTH, -3);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        //查询教练组信息
        Map map2 = coaceGroupController.getPageCoaceGroup(request, "", "", "0");
        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");


        //查询科目二分车信息
        Sharecartworeg sharecartworeg = sharecartworegService.selectSharecartworegByFid(fid);

        if (sharecartworeg == null) {
            return "/error/not_data";
        }
        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);

        request.setAttribute("createName", user.getName());
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb2", map2.get("pb"));
        request.setAttribute("coacegroups", map2.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("sharecartworegList", sharecartworeg);
        request.setAttribute("auditState", selectProcessState(user, sharecartworeg.getFnumber()));
        request.setAttribute("activitiBPMN_KEY", ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC);

        return "/backHome/practiseCAR/ShareCarTwoReg/updateShareCarTwoReg";
    }

    /**
     * @Author lcx
     * @Date 2017/11/24 0024 上午 9:36
     * 添加分车信息 传入state==1做修改操作
     */

    @RequestMapping(value = "/add_shareCarTwoReg")
    public String addShareCarTwoReg(HttpServletRequest request, Sharecartworeg sharecartworeg, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        sharecartworeg.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        sharecartworeg.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        sharecartworeg.setFcreatetime(createTime);
        //修改时间
        sharecartworeg.setFcreatorid(user.getFid());


        //收集子类信息
        String[] jlznamebm = request.getParameterValues("jlznamebm");
        String[] jlzname = request.getParameterValues("cfjlgroupid");
        String[] cfduizhang = request.getParameterValues("cfduizhang");
        String[] jlname = request.getParameterValues("cfcoachid");
        String[] cfcoachphone = request.getParameterValues("cfcoachphone");
        String[] cfcarcx = request.getParameterValues("cfcarcx");
        String[] cfcarnumber = request.getParameterValues("cfcarnumber");
        String[] cfstudentid = request.getParameterValues("cfstudentid");
        String[] xyname = request.getParameterValues("xyname");
        String[] cfstudentno = request.getParameterValues("cfstudentno");
        String[] cfidcardno = request.getParameterValues("cfidcardno");
        String[] cfstuvip = request.getParameterValues("cfstuvip");
        String[] cfstubillstate = request.getParameterValues("cfstubillstateid");
        String[] cffristexam = request.getParameterValues("cffristexam");
        String[] cfkeyhgsj = request.getParameterValues("cfkeyhgsj");
        String[] cflastkssj = request.getParameterValues("cflastkssj");
        String[] cfkscs = request.getParameterValues("cfkscs");
        String[] cfsex = request.getParameterValues("cfsex");
        String[] cfphone = request.getParameterValues("cfphone");
        String[] cfmobile = request.getParameterValues("cfmobile");
        String[] cfsqzjcx = request.getParameterValues("cfsqzjcx");
        String[] cfbdyd = request.getParameterValues("cfbdyd");
        String[] cfpxlx = request.getParameterValues("cfpxlx");
        String[] cftjr = request.getParameterValues("cftjr");
        String[] cfclazz = request.getParameterValues("cfclazz");
        String[] cfyishou = request.getParameterValues("cfyishou");
        String[] cfysje = request.getParameterValues("cfysje");
        String[] cfyouhui = request.getParameterValues("cfyouhui");
        String[] cfqianfei = request.getParameterValues("cfqianfei");
        String[] cfremark = request.getParameterValues("cfremark");

        //添加练车  一个事物处理
        sharecartworegService.addsharecartworeg(state, sharecartworeg, jlznamebm, jlzname, cfduizhang,
                jlname, cfcoachphone, cfcarcx, cfcarnumber, cfstudentid, xyname, cfstudentno, cfidcardno,
                cfstuvip, cfstubillstate, cffristexam, cfkeyhgsj, cfsex, cflastkssj, cfkscs, cfphone, cfmobile,
                cfsqzjcx, cfbdyd, cfpxlx, cftjr, cfclazz, cfyishou, cfysje, cfyouhui, cfqianfei, cfremark);

        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二分车新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_Sharecartworeg?alertType=bc";
    }

    /**
     * @Author lcx
     * @Date 2017/11/24 0024 上午 9:12
     * 更新数据
     */
    @RequestMapping(value = "/update_sharecartworeg")
    public String updateRecordin(HttpServletRequest request, Sharecartworeg sharecartworeg) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        sharecartworeg.setFlastupdatetime(createTime);
        //修改人id
        sharecartworeg.setFlastupdateuserid(user.getFid());

        addShareCarTwoReg(request, sharecartworeg, "1");

        return "redirect:/DrivingSys/querySharecartworeg/look.action?state=first&alertType=qd";
    }

    @RequestMapping(value = "delete_sharecartworeg")
    public String deleteSharecartworeg(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        sharecartworegService.deleteBySharecartworegKey(deleteId, fnumber);
        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二分车进行删除", null, user.getFid());


        return "redirect:/DrivingSys/querySharecartworeg/look.action?state=first";
    }

    /**
     * @Author lcx
     * @Date 2017/11/21 0021 上午 10:37
     * ajax查询教练
     */
    @RequestMapping(value = "/selectPersonByFidAsPage")
    @ResponseBody
    public Object selPositiongradeById(@RequestParam(value = "id", required = false) String id) throws Exception {
        List<Sharecartworegentry> personArrayList = new ArrayList<Sharecartworegentry>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            Sharecartworegentry sharecartworegentry = sharecartworegService.queryPersonCarByFid(ids[i]);
            personArrayList.add(sharecartworegentry);
        }
        return personArrayList;
    }

    //--------------------------------------------------科目二流程------------------------------------------------
    ActitiviUtil activitiUtil = new ActitiviUtil();

    /**
     * 提交后开始流程并推进至下一节点
     *
     * @param request
     * @param fnumber 单据编号
     */
    @RequestMapping(value = "/startProcessSubjectTwoAllowCar")
    @ResponseBody
    public int startProcess(HttpServletRequest request, String fnumber, String fid, String auditState) {
        // String flowKey = ActivitiKey.FNUMBER_KM2FC; //流程的id

        //获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC, fnumber);
        if ("noProcess".equals(auditState) || "processEnd".equals(auditState)) {
            //启动流程并设置流程变量
            String piID = activitiUtil.creatFlow(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC, map);
            System.out.println("单据编号:" + fnumber);

            //4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
            Message message = activitiUtil.completeFlowByPiID(piID);
            if (message != null) {
                message.setMessage("科目二分车-审核 #" + fnumber + "# ");//消息内容
                message.setUrl("/go_update_shareCarTwoReg?fid=" + fid);//详细路径
                message.setEditUrl("/auditProcessSubjectTwoAllotCar?fid=" + fid + "&fnumber=" + fnumber);
                messageService.insert(message);
            }
        }


        //--------------判断有历史流程添加此方法------------
        if (auditState.equals("processing")) {
            /*审核过程中的单据被打回调此方法*/
            Message message2 = activitiUtil.complteFlowByVariable(
                    ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC,  //指定要启动的流程定义
                    fnumber                     //流程变量
            );

            if (message2 != null) {
                message2.setMessage("科目二分车-审核 #" + fnumber + "# ");//消息内容
                message2.setUrl("/go_update_shareCarTwoReg?fid=" + fid);//详细路径
                message2.setEditUrl("/auditProcessSubjectTwoAllotCar?fid=" + fid + "&fnumber=" + fnumber);
                messageService.insert(message2);
            }
        }


        //---------------------修改单据信息--------
        Sharecartworeg sharecartworeg = new Sharecartworeg();
        /*//获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        //获取当前时间
        String updateTime = TimeFormat.timeFormat(new Date());

        //修改时间
        sharecartworeg.setFlastupdatetime(updateTime);
        sharecartworeg.setFauditorid(user.getFid());*/
        sharecartworeg.setFid(fid);
        sharecartworeg.setCfbillstate(Long.valueOf("4"));
        sharecartworegMapper.updateByPrimaryKeySelective(sharecartworeg);
        //添加日志
        //customLogService.addLog("计时收费", "对计时收费提交操作单据编号 " + fnumber, null, user.getFid());

        sharecartworegService.addLog(fid, "1");


        return 1;
    }


    //点击审核
    @RequestMapping(value = "/auditProcessSubjectTwoAllotCar")
    @ResponseBody
    public int auditProcess(HttpServletRequest request, String fnumber,
                            String message, @RequestParam(defaultValue = "1", value = "state") Integer state, String fid,
                            @RequestParam(defaultValue = "", value = "cfstubillstateid[]") String[] cfstubillstateid,
            /*@RequestParam(defaultValue = "", value = "cfstudentid[]") String[] cfstudentid,*/
                            String cflcsjid) {

        String[] cfstudentid = sharecartworegentryMapper.selectStudentidByParentid(fid);
        //获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        Object returnMsg = activitiUtil.auditComplteMessage(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC, fnumber, state, message);
        int endOrNot = 0;    //判断流程状态（1.通过 2.通过且结束 3.当前用户不是经办人）
        //System.out.println("通过原因:"+message);
        Sharecartworeg sharecartworeg = new Sharecartworeg();
        //获取当前用户
        //User user = (User) request.getSession().getAttribute("user");
        //获取当前时间
        String updateTime = TimeFormat.timeFormat(new Date());


        if (returnMsg instanceof Message) {
            Message resultMsg = (Message) returnMsg;
            resultMsg.setMessage("科目二分车-审核 #" + fnumber + "# ");//消息内容
            resultMsg.setUrl("/go_update_shareCarTwoReg?fid=" + fid);//详细路径
            resultMsg.setEditUrl("/auditProcessSubjectTwoAllotCar?fid=" + fid + "&fnumber=" + fnumber);
            messageService.insert(resultMsg);


            /*sharecartworeg.setFlastupdatetime(updateTime);
            sharecartworeg.setFauditorid(user.getFid());
            sharecartworeg.setCheckName(user.getName());*/
            sharecartworeg.setFid(fid);

            if (state == 0) {
                sharecartworeg.setCfbillstate(Long.valueOf("3"));
                sharecartworegMapper.updateByPrimaryKeySelective(sharecartworeg);
            }
            endOrNot = 1;
            System.out.println("此流程成功推进");
        } else if (activitiUtil.notAssign.equals(returnMsg)) {
            System.out.println("当前用户不是要求的经办人!");
            endOrNot = 3;

        } else if (activitiUtil.FINISH.equals(returnMsg)) {
            //修改时间
            sharecartworeg.setFlastupdatetime(updateTime);
            sharecartworeg.setFauditorid(user.getFid());
            sharecartworeg.setFid(fid);
            sharecartworeg.setCfbillstate(Long.valueOf("5"));
            sharecartworegMapper.updateByPrimaryKeySelective(sharecartworeg);

            if (cflcsjid == null){
                Sharecartworegentry tem = sharecartworegMapper.selectByFnumber(fnumber);
                cflcsjid =tem.getCflcsjid();

            }
            sharecartworegService.modifyStudentsState(cfstudentid, cfstubillstateid, cflcsjid);

            System.out.println("此流程成功推进，并且此流程已经结束");
            endOrNot = 2;
            sharecartworegMapper.updateByPrimaryKeySelective(sharecartworeg);

        } else if (activitiUtil.SUCCESS.equals(returnMsg)) {
            if (state == 0) {
                sharecartworeg.setCfbillstate(Long.valueOf("3"));
            }
        } else if (activitiUtil.notTask.equals(returnMsg)) {
            endOrNot = 0;
            System.out.println("没有找到正在进行的相关流程");
        }

        sharecartworegService.addLog(fid, "2");


        return endOrNot;
    }


    //3.反审核
    @RequestMapping(value = "/failAuditProcessSubjectTwoAllotCar")
    @ResponseBody
    public int failAuditProcess(HttpServletRequest request, String fnumber,
                                String fid, String message, String auditState,
                                @RequestParam(defaultValue = "", value = "cfstubillstateid[]") String[] cfstubillstateid,
                                @RequestParam(defaultValue = "", value = "cfstudentid[]") String[] cfstudentid,
                                String cflcsjid) throws Exception {
        //获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        /*反审核不需要 经办人*/
        if (auditState.equals("processing") || true) {
            Object result = activitiUtil.jumpActivtiMessage(
                    ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC,
                    fnumber,                  //单据
                    message
            );

            String returnMessage = null;
            if (result instanceof Message) {
                /*Message resultMsg = (Message) result;
                resultMsg.setMessage("科目二分车-反审核 #" + fnumber + "# ");//消息内容
                resultMsg.setUrl("/go_update_shareCarTwoReg?fid=" + fid);//详细路径
                messageService.insert(resultMsg);*/
                System.out.println("反审核成功");
                returnMessage = "反审核成功！";
            } else if (activitiUtil.SUCCESS.equals(result)) {

            } else if (activitiUtil.notActiviti.equals(result)) {
                System.out.println("找不到流程节点");
                returnMessage = "找不到流程节点";
            } else if (activitiUtil.notTask.equals(result)) {
                System.out.println("没有找到任务");
                returnMessage = "没有找到任务";
            }
        } else if (auditState.equals("processEnd")) {
            Message message2 = activitiUtil.getMessage(
                    ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC,
                    fnumber                  //单据
            );

            if (message2 != null) {
                /*message2.setMessage("科目二分车-反审核 #" + fnumber + "# ");//消息内容
                message2.setUrl("/go_update_shareCarTwoReg?fid=" + fid);//详细路径
                messageService.insert(message2);*/
            }
        }

        Sharecartworeg sharecartworeg = new Sharecartworeg();
        /*
        //获取当前时间
        String updateTime = TimeFormat.timeFormat(new Date());

        //修改时间
        sharecartworeg.setFlastupdatetime(updateTime);
        sharecartworeg.setFauditorid(user.getFid());*/
        sharecartworeg.setCfbillstate(Long.valueOf("3"));
        sharecartworeg.setFid(fid);

        sharecartworegService.addLog(fid, "3");
        sharecartworegService.modifyStudentsState2(cfstudentid, cfstubillstateid, cflcsjid);

        sharecartworegMapper.updateByPrimaryKeySelective(sharecartworeg);
        return 0;
    }


    //判断流程状态
    public String selectProcessState(User user, Object fnumber) {
        String result = activitiUtil.getTaskStateByUser(
                ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.FNUMBER_KM2FC_GL : ActivitiKey.FNUMBER_KM2FC_NC,
                fnumber                 //单据
        );

        if (activitiUtil.notTask.equals(result)) {
            System.out.println("改单据没有对应流程");            //没有历史流程（从来没有过流程的“新单据”）
            return "noProcess";

        } else if (activitiUtil.FINISH.equals(result)) {
            System.out.println("流程已结束");                //只有有历史流程
            return "processEnd";
        }//剩下两种是该任务进行中
        else if (activitiUtil.notAssign.equals(result)) {
            System.out.println("经办人不匹配");                //正在进行的流程，但是经办人跟当前用户不匹配
            return "peopleNot";
        } else if (activitiUtil.ISPOWER.equals(result)) {
            System.out.println("当前用户可以审核该单据");            /**正在进行的流程，且当前用户能够审核
             * 如果是进入可提交的详情页面，这个标记表示
             * 此流程进行中，即用户点击提交只需推进流程即可
             */
            return "processing";
        } else {
            return "nothing";
        }
    }

    @RequestMapping("/queryShareCarTwoRegXls")
    public String queryShareCarTwoRegXls(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                         @RequestParam(defaultValue = "", value = "fdescription") String fdescription,
                                         @RequestParam(defaultValue = "", value = "cfstudentname") String cfstudentname,
                                         @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                         @RequestParam(defaultValue = "", value = "endTime") String endTime) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "教练", "学员", "学员编号", "身份证号码",
                "是否vip", "学员状态", "性别", "手机", "电话", "申领类型", "本地/异地", "培训类型", "推荐人", "教练手机",
                "车型", "车牌号", "练车时间", "补/初", "科目一合格时间", "考试次数", "上次不及格时间", "备注", "教练组", "教练组编码",
                "是否组长", "应收金额", "已收", "优惠", "欠费", "班级"};
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 3000, 6000, 6000,
                2000, 7000, 2000, 4000, 4000, 3000, 3000, 3000, 2000, 4000,
                3000, 4000, 7000, 3000, 6000, 2000, 6000, 7000, 4000, 3000,
                3000, 3000, 3000, 3000, 3000, 3000};

        List<Sharecartworegentry> sharecartworegentryList = sharecartworegService.selectSharecartworegAsXls(fnumber, fdescription, cfstudentname, beginTime, endTime, user.getFcompanyid());


        for (Sharecartworegentry sharecartworegentry : sharecartworegentryList) {
            data.add(sharecartworegentry.getFnumber());
            data.add(sharecartworegentry.getFbizdate());
            data.add(sharecartworegentry.getFdescription());
            data.add(sharecartworegentry.getCheckName());
            data.add(sharecartworegentry.getCreateName());
            data.add(stateToString.billsState(sharecartworegentry.getCfbillstate()));
            data.add(sharecartworegentry.getJlname());
            data.add(sharecartworegentry.getXyname());
            data.add(sharecartworegentry.getCfstudentno());
            data.add(sharecartworegentry.getCfidcardno());
            data.add(stateToString.cfstuvip(sharecartworegentry.getCfstuvip())); //是否vip
            data.add(stateToString.studentState(sharecartworegentry.getCfstubillstate())); //学员状态
            data.add(stateToString.sex(sharecartworegentry.getCfsex()));
            data.add(sharecartworegentry.getCfmobile());
            data.add(sharecartworegentry.getCfphone());
            data.add(sharecartworegentry.getCfsqzjcx());
            data.add(stateToString.cfbdyd(sharecartworegentry.getCfbdyd()));//本地异地
            data.add(sharecartworegentry.getCfpxlx());//培训类型
            data.add(sharecartworegentry.getCftjr());//推荐人
            data.add(sharecartworegentry.getCfcoachphone());//教练手机
            data.add(sharecartworegentry.getCfcarcx());//车型
            data.add(sharecartworegentry.getCfcarnumber());//车牌
            data.add(sharecartworegentry.getLctime());
            data.add(sharecartworegentry.getCffristexam());//（初考，补考，缺考）
            data.add(sharecartworegentry.getCfkeyhgsj());
            data.add(sharecartworegentry.getCfkscs());
            data.add(sharecartworegentry.getCflastkssj());
            data.add(sharecartworegentry.getCfremark());
            data.add(sharecartworegentry.getJlzname());//教练组
            data.add(sharecartworegentry.getJlznamebm());//教练组编码
            data.add(stateToString.cfstuvip(sharecartworegentry.getCfduizhang()));//是否组长
            data.add(sharecartworegentry.getCfyishou());
            data.add(sharecartworegentry.getCfysje());
            data.add(sharecartworegentry.getCfyouhui());
            data.add(sharecartworegentry.getCfqianfei());
            data.add(sharecartworegentry.getCfclazz());


        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "科目二分车" + TimeFormat.getNowTime2() + ".xls", "科目二分车", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/querySharecartworeg/look.action?state=first";
    }

    /**
     * 科目二分车导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/importPracticeDrivingData")
    @ResponseBody
    public Object importPracticeDrivingData(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        /**
         * 获取用户
         */
        User user = (User) request.getSession().getAttribute("user");

        /**
         * 获取表格数据
         */
        ImportExcelUtil_MrWu importExcel_MrWu = new ImportExcelUtil_MrWu();
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile(GetFid.UUIDIntoFid(), prefix);
        // MultipartFile to File
        file.transferTo(excelFile);
        List<List<Object>> list = importExcel_MrWu.importExcel(excelFile);//获取表格信息
        String lcNumber = ((String) list.get(0).get(1)).trim();//练车编码
        String plan = exerciseCarPlanService.selExerciseCarPlanByFnumer(lcNumber, user.getFcompanyid());
        String cflcsj = changecoachTwoService.importPracticeDrivingData(plan);//练车时间

        if (cflcsj == null) {
            return "-1";
        }

        /**
         * 主表数据
         */
        Sharecartworeg sharecartworeg = new Sharecartworeg();
        //公司id
        sharecartworeg.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        sharecartworeg.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.getNowTime();
        //单据
        sharecartworeg.setFnumber(GetFnumber.fnumbers("KMEFC"));
        //业务时间
        sharecartworeg.setFbizdate(createTime);
        //单据状态
        sharecartworeg.setCfbillstate(3L);
        //练车时间
        sharecartworeg.setCflcsjid(plan);
        //创建时间
        sharecartworeg.setFcreatetime(createTime);
        //修改时间
        sharecartworeg.setFcreatorid(user.getFid());
        //创建人
        sharecartworeg.setCreateName(user.getUserName());

        /**
         * 统计失败
         */
        int count = 0;//导入失败计数
        List<Map<String, String>> errorStu = new ArrayList<>();//导入失败的学员
        Map<String, List<Map<String, String>>> accomplishmsg = new HashMap<>();//最后的信息




            /**
             * 初始化收集子类信息数组
             */
            int k = 0;
            String[] jlznamebm = new String[list.size() - 2];//教练组编码
            String[] jlzname = new String[list.size() - 2];//教练组名称
            String[] cfduizhang = new String[list.size() - 2];//教练是否是组长
            String[] jlname = new String[list.size() - 2];//教练名
            String[] cfcoachphone = new String[list.size() - 2];//教练电话号码
            String[] cfcarcx = new String[list.size() - 2];//车型
            String[] cfcarnumber = new String[list.size() - 2];//车牌号
            String[] cfstudentid = new String[list.size() - 2];//学员id
            String[] xyname = new String[list.size() - 2];//学员名称
            String[] cfstudentno = new String[list.size() - 2];//学员编号
            String[] cfidcardno = new String[list.size() - 2];//学员身份证号码
            String[] cfstuvip = new String[list.size() - 2];//是否是vip
            String[] cfstubillstate = new String[list.size() - 2];//学员状态
            String[] cffristexam = new String[list.size() - 2];//出或补
            String[] cfkeyhgsj = new String[list.size() - 2];//合格时间
            String[] cflastkssj = new String[list.size() - 2];//考试时间
            String[] cfkscs = new String[list.size() - 2];//考试次数
            String[] cfsex = new String[list.size() - 2];//学员性别
            String[] cfphone = new String[list.size() - 2];//学员电话号码
            String[] cfmobile = new String[list.size() - 2];//学员手机号码
            String[] cfsqzjcx = new String[list.size() - 2];//申请类型
            String[] cfbdyd = new String[list.size() - 2];//本地异地
            String[] cfpxlx = new String[list.size() - 2];//培训类型
            String[] cftjr = new String[list.size() - 2];//推荐人
            String[] cfclazz = new String[list.size() - 2];//班级
            String[] cfyishou = new String[list.size() - 2];//已收
            String[] cfysje = new String[list.size() - 2];//应收金额
            String[] cfyouhui = new String[list.size() - 2];//优惠
            String[] cfqianfei = new String[list.size() - 2];//欠费
            String[] cfremark = new String[list.size() - 2];//备注

        /**
         * 查学员练车预约记录
         */
        for (int i = 2; i < list.size(); i++) {

            Map<String, String> mapParameter = new HashMap<>();// 构造Map参数

            String stuName = ((String) list.get(i).get(3)).trim();//表格中学员姓名
            String stuIdCard = ((String) list.get(i).get(2)).trim();//表格中学员身份证
            String bgJlName = ((String) list.get(i).get(1)).trim();//表格中教练名字
            String bgCarNumber = ((String) list.get(i).get(0)).trim();//表格中车牌

            /**
             * 查学员详细信息
             */
            List<Student> students = studentService.selectStudentByCfidcardno(stuIdCard);//通过身份证查询学员
            if (students == null || students.size() == 0) {
                /**
                 * 存入错误信息
                 */
                count++;
                mapParameter.put("name", stuName);
                mapParameter.put("mes", "学员信息查询失败！");
                errorStu.add(mapParameter);
                continue;
            }
            Student stu = recordinentryService.selectStudentById(students.get(0).getFid());//通过学员id查询详细学员信息


            /* 排除 学生状态对de的数据*/
            String studentstate = String.valueOf(students.get(0).getCfstudentstate());
            if (!("2".equals(studentstate) || "5".equals(studentstate)|| "7".equals(studentstate)|| "17".equals(studentstate)
                    || "19".equals(studentstate)|| "20".equals(studentstate)|| "21".equals(studentstate))) {
                /**
                 * 存入错误信息
                 */
                count++;
                mapParameter.put("name", stuName);
                mapParameter.put("mes", "该学员预约失败！（学生状态不符合）");
                errorStu.add(mapParameter);
                continue;
            }
            /**
             * 查询学员练车预约记录
             */
            List<Sharecarsub> sharecarsubs = sharecarsubService.selectSharecarsubentryXlss(lcNumber, stuName, stuIdCard, "", "2", "", "", "1",GetUserSession.getUserSession(request));
            if (sharecarsubs == null) {
                /**
                 * 存入错误信息
                 */
                count++;
                mapParameter.put("name", stuName);
                mapParameter.put("mes", "该学员预约失败！");
                errorStu.add(mapParameter);
                continue;
            }

            /**
             * 查教练信息
             */
            List<Person> personList = personService.selectPersonForByName( bgJlName,GetUserSession.getUserSession(request));
            if (personList == null || personList.size() == 0) {
                /**
                 * 存入错误信息
                 */
                mapParameter.put("name", stuName);
                mapParameter.put("mes", "教练信息出错！");
                errorStu.add(mapParameter);
                count++;
                continue;
            }
            List<Sharecartworegentry> personArrayList = (List<Sharecartworegentry>) selPositiongradeById(personList.get(0).getFid());


            /**
             * 将预约成功的学员放入数组
             */
            jlznamebm[k] = personArrayList.get(0).getJlbumber();//教练组编码
            if (personArrayList.get(0).getJlbumber() == null) {
                jlznamebm[k] = "";
            }
            jlzname[k] = personArrayList.get(0).getJlzname();//教练组名称
            if (personArrayList.get(0).getJlzname() == null) {
                jlzname[k] = "";
            }
            cfduizhang[k] = personArrayList.get(0).getCfcoachid();//教练是否是组长
            if (personArrayList.get(0).getCfcoachid() == null) {
                cfduizhang[k] = "";
            }
            cfcoachphone[k] = (String) personArrayList.get(0).getCfphone();//教练电话号码
            if ((String) personArrayList.get(0).getCfphone() == null) {
                cfcoachphone[k] = "";
            }
            cfcarcx[k] = (String) personArrayList.get(0).getCfcartype();//车型
            if ((String) personArrayList.get(0).getCfcartype() == null) {
                cfcarcx[k] = "";
            }
            jlname[k] = personArrayList.get(0).getFid();//教练名


            cfcarnumber[k] = bgCarNumber;//车牌号
            cfstudentid[k] = stu.getFid();//学员id
            if (stu.getFid() == null) {
                cfstudentid[k] = "";
            }
            xyname[k] = stuName;//学员名称
            cfstudentno[k] = (String) stu.getFnumber();//学员编号
            if ((String) stu.getFnumber() == null) {
                cfstudentno[k] = "";
            }
            cfidcardno[k] = stuIdCard;//学员身份证号码
            cfstuvip[k] = stu.getCfvip();//是否是vip
            if (stu.getCfvip() == null) {
                cfstuvip[k] = "";
            }
            cfstubillstate[k] = stu.getCfstudentstate() + "";//学员状态
            if (stu.getCfstudentstate() == null) {
                cfstubillstate[k] = "";
            }
            if (stu.getCfkmsbjgsj() == null) {
                cffristexam[k] = "初考";//初或补
            } else {
                cffristexam[k] = "补考";//初或补
            }
            cfkeyhgsj[k] = stu.getCfkmyherq();//合格时间
            if (stu.getCfkmyherq() == null) {
                cfkeyhgsj[k] = "";
            }
            cflastkssj[k] = stu.getCfkmyksqksj();//考试时间
            if (stu.getCfkmeksqksj() == null) {
                cflastkssj[k] = "";
            }
            cfkscs[k] = students.get(0).getCfkmekss() + "";//考试次数
            if (students.get(0).getCfkmekss() + "" == null) {
                cfkscs[k] = "";
            }
            if (students.get(0).getCfsex() == 1) {
                cfsex[k] = "男";//学员性别
            } else {
                cfsex[k] = "女";//学员性别
            }
            cfphone[k] = (String) stu.getCfsjhm();//学员电话号码
            if ((String) stu.getCfsjhm() == null) {
                cfphone[k] = "";
            }
            cfmobile[k] = (String) stu.getCflxdh();//学员手机号码
            if ((String) stu.getCflxdh() == null) {
                cfmobile[k] = "";
            }
            cfsqzjcx[k] = stu.getCfslzjcxdh();//申请类型
            if (stu.getCfslzjcxdh() == null) {
                cfsqzjcx[k] = "";
            }
            if (stu.getCflocal() == 1) {
                cfbdyd[k] = "本地";//本地异地
            } else {
                cfbdyd[k] = "异地";//本地异地
            }
            cfpxlx[k] = stu.getCftrainTypeNAME();//培训类型
            if (stu.getCftrainTypeNAME() == null) {
                cfpxlx[k] = "";
            }
            cftjr[k] = stu.getCftjrName();//推荐人
            if (stu.getCftjrName() == null) {
                cftjr[k] = "";
            }
            cfclazz[k] = stu.getCfclazzName();//班级
            if (stu.getCfclazzName() == null) {
                cfclazz[k] = "";
            }
            cfyishou[k] = stu.getCfamount() + "";//已收
            if (stu.getCfamount() + "" == null) {
                cfyishou[k] = "";
            }
            cfysje[k] = stu.getCfreceived() + "";//应收金额
            if (stu.getCfreceived() + "" == null) {
                cfysje[k] = "";
            }
            cfyouhui[k] = stu.getCffavorable() + "";//优惠
            if (stu.getCffavorable() + "" == null) {
                cfyouhui[k] = "";
            }
            cfqianfei[k] = stu.getCfarrearage() + "";//欠费
            if (stu.getCfarrearage() + "" == null) {
                cfqianfei[k] = "";
            }
            cfremark[k] = (String) stu.getCfdesc();//备注
            if ((String) stu.getCfdesc() == null) {
                cfremark[k] = "";
            }
            k++;


        }
        /**88
         * 添加科目二分车数据
         */
        sharecartworegService.addsharecartworeg("0", sharecartworeg, jlznamebm, jlzname, cfduizhang,
                jlname, cfcoachphone, cfcarcx, cfcarnumber, cfstudentid, xyname, cfstudentno, cfidcardno,
                cfstuvip, cfstubillstate, cffristexam, cfkeyhgsj, cfsex, cflastkssj, cfkscs, cfphone, cfmobile,
                cfsqzjcx, cfbdyd, cfpxlx, cftjr, cfclazz, cfyishou, cfysje, cfyouhui, cfqianfei, cfremark);

        deleteFile(excelFile); //程序结束时，删除临时文件
        accomplishmsg.put("failed", errorStu);
        return accomplishmsg;
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 科目二分车导出数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/exportPracticeDrivingData")
    public String exportPracticeDrivingData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "科目二分车导入模板.xls";
        String download = request.getSession().getServletContext().getRealPath("/xls/"); //获取下载路劲
        File file = new File(download +"/"+ fileName);  //根据文件路径获得File文件
        response.setContentType("application/msexcel;charset=GBK");
        //文件名
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.getBytes(), "ISO8859-1") + "");
        response.setContentLength((int) file.length());
        byte[] buffer = new byte[4096];// 缓冲区
        BufferedOutputStream output = null;
        BufferedInputStream input = null;
        try {
            output = new BufferedOutputStream(response.getOutputStream());
            input = new BufferedInputStream(new FileInputStream(file));
            int n = -1;
            //遍历，开始下载
            while ((n = input.read(buffer, 0, 4096)) > -1) {
                output.write(buffer, 0, n);
            }
            output.flush();   //不可少
            response.flushBuffer();//不可少
        } catch (Exception e) {
            //异常自己捕捉
        } finally {
            //关闭流，不可少
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
        return "redirect:/DrivingSys/queryChangecoachTwo/look.action?state=first";
    }
}
